// @ts-nocheck
import { observable, makeObservable, action, runInAction, computed, toJS } from 'mobx';
import { Service } from './service';
import { message } from 'antd';
import { getDateTime } from '@/utils';
import { svgPath } from '@/types/constant';

export default class Store {
  readonly service: Service;

  @observable
  loading: boolean = false;

  @observable
  orderLoading: boolean = false;

  @observable
  searchValues: any = {
  };

  @observable
  treeSearchValues: any = {
    current: 1,
    size: 10,
  }

  @observable
  batchOrderList: any[] = [];

  @observable
  activeIndex: number = null;

  @observable
  elements: IElement[] = [];

  @observable
  links: ITask[] = [];

  @observable
  taskList: ITask[] = [];

  @observable
  activeBatchOrder: any = {};

  @observable
  activeTaskList: any[] = [];

  @observable
  taskResourceInfo: any = {};

  @observable
  visible: boolean = false;

  @observable
  dialogLoading: boolean = false;

  @observable
  file: string = '';

  @observable
  threed_file: string = '';

  @observable
  orderTree: any[] = [];

  @observable
  orderTreeTotal: number = 0;

  constructor() {
    makeObservable(this);
    this.service = new Service();
  }

  @action.bound
  clear() {
    this.file = null;
    this.threed_file = null;
    this.activeIndex = null;
    this.batchOrderList = [];
    this.elements = [];
    this.taskList = [];
    this.activeBatchOrder = {};
    this.activeTaskList = [];
    this.taskResourceInfo = {};
  }

  @action.bound
  setSearchValues(payload: any) {
    this.clear();
    this.searchValues = {
      ...this.searchValues,
      ...payload
    };
    this.getCanAssignmentTask();
  }

  @action.bound
  searchTree() {
    this.orderLoading = true;
    this.service.searchTree(this.treeSearchValues).then(data => {
      this.orderTree = data?.records || [];
      this.orderTreeTotal = data?.total;
      if (!this.searchValues?.batch_order_id && data?.records?.length) {
        const batchOrderList = data.records[0].batch_order_list || [];
        if (batchOrderList.length) {
          const order=  batchOrderList[0];
          this.setSearchValues({
            batch_order_num: order['batch_order_num'],
            batch_order_id: order['id'],
            priority: Number(order['priority'])
          })
        }
      }
    }).finally(() => {
      this.orderLoading = false;
    })
  }

  @action.bound
  setTreeSearchValues(payload: any) {
    this.treeSearchValues = { ...this.treeSearchValues, ...payload };
    this.searchTree();
  }

  @action.bound
  onChange(params: any) {
    const data = toJS(this.batchOrderList);
    const order = toJS(this.activeBatchOrder);
    Object.assign(data[this.activeIndex], params);
    Object.assign(order, params);
    runInAction(() => {
      this.batchOrderList = data;
      this.activeBatchOrder = order;
    })
  }

  @action.bound
  setActiveIndex(index: number) {
    const id = this.batchOrderList?.[index]?.id;
    if (id) {
      this.activeIndex = index;
      this.activeBatchOrder = this.batchOrderList[index];
      this.getTaskResourceOccupyInfo(id);
    }
  }

  @action.bound
  getTaskResourceOccupyInfo(id: string) {
    this.service.getTaskResourceOccupyInfo({ id }).then(data => {
      const keys = ['','aps_station_id','aps_device_id','aps_station_id','aps_user_id','aps_line_id'];
      const aps_resource_id = data[keys[data.capacity || 2]];
      data.aps_resource_id = aps_resource_id;
      data?.resource_list?.forEach(item => {
        item.key = item.id;
        item.open = true;
        item.type = 'project';
        item.render = 'split';
        item.children = [];
        switch(item.capacity) {
          case 1:
          case 3: {
            item.resource_num = item.device_num;
            item.resource_name = item.device_num;
            item.text = item.device_num;
            item.resource_id = item.id;
            break;
          }
          case 2: {
            item.resource_num = item.device_num;
            item.resource_name = item.device_num;
            item.text = item.device_num;
            item.resource_id = item.id;
            break;
          }
          case 4: {
            item.resource_num = item.device_num;
            item.resource_name = item.device_num;
            item.text = item.device_num;
            item.resource_id = item.id;
            break;
          }
          case 5: {
            item.resource_num = item.device_num;
            item.resource_name = item.device_num;
            item.text = item.device_num;
            item.resource_id = item.id;
            break;
          }
          default: {
            item.resource_num = item.device_num;
            item.resource_name = item.device_num;
            item.text = item.device_num;
            item.resource_id = item.device_id;
            break;
          }
        }
        item.is_aps = item.resource_id === aps_resource_id;
      });
      data?.resource_occupy_list?.forEach(item => {
        switch(item.capacity) {
          case 1:
          case 3: {
            item.resource_num = item.work_station_num;
            item.resource_name = item.work_station_name;
            item.label = item.work_station_name;
            item.text = item.work_tation_name;
            item.color = item.station_color;
            item.resource_id = item.work_station_id;
            break;
          }
          case 2: {
            item.resource_num = item.work_device_num;
            item.resource_name = item.work_device_name;
            item.label = item.work_device_name;
            item.text = item.work_device_name;
            item.color = item.device_color;
            item.resource_id = item.work_device_id;
            break;
          }
          case 4: {
            item.resource_num = item.work_user_num;
            item.resource_name = item.work_user_name;
            item.label = item.work_user_name;
            item.text = item.work_user_name;
            item.color = item.user_color;
            item.resource_id = item.work_user_id;
            break;
          }
          case 5: {
            item.resource_num = item.work_device_num;
            item.resource_name = item.work_device_name;
            item.label = item.work_device_name;
            item.text = item.work_device_name;
            item.color = item.device_color;
            item.resource_id = item.work_device_id;
            break;
          }
          default: {
            item.resource_num = item.work_device_num;
            item.resource_name = item.work_device_name;
            item.label = item.work_device_name;
            item.text = item.work_device_name;
            item.color = item.device_color;
            item.resource_id = item.work_device_id;
            break;
          }
        }
        item.is_aps = item.resource_id === aps_resource_id;
        item.key = item.id;
        item.start_date = item.work_start;
        item.end_date = item.work_end;
        const resource = data?.resource_list?.find(r => r.capacity === item.capacity && r.resource_id === item.resource_id);
        item.section_id = resource?.id;
      })
      runInAction(() => {
        this.taskResourceInfo = data || {};
        const elements = [];
        const links = [];
        data?.resource_list?.forEach(ele => {
          const children = (data?.resource_occupy_list || []).filter(item => item.section_id === ele.id);
          ele.start_date = children[0]?.work_start || getDateTime();
          ele.end_date = children[children.length - 1]?.work_end || getDateTime();
          elements.push(ele);
          children.forEach((task, index) => {
            elements.push({
              ...task,
              id: task.id,
              parent: ele.id,
              text: `<div style="position: relative;">
                ${task.batch_order_num} #${task.mbom_num}
                ${task.task_flag ? `<img src="${svgPath}sanjiao.svg" width="60" style="position:absolute;left: 50%;top:15px;transform:translateX(-50%);z-index:10;" />` : ''}
              </div>`,
              start_date: task.work_start,
              end_date: task.work_end,
            });
            if (index > 0 && index < (children.length - 1)) {
              links.push({
                id: Math.random(),
                source: children[index - 1].id,
                target: task.id,
                type: '0'
              })
            }
          })
        })
        this.elements = elements;
        this.links = links;
        this.taskList = data?.resource_occupy_list || [];
      })
    })
  }

  @action.bound
  getCanAssignmentTask() {
    this.service.getCanAssignmentTask({
      batch_order_id: this.searchValues.batch_order_id
    }).then(data => {
      const { task_list, file, threed_file } = data;
      runInAction(() => {
        this.batchOrderList = (task_list ?? []).map(item => {
          return {
            ...item,
            color: item.bom_color,
            aps_color: item.bom_color,
            work_start: item.work_start || item.aps_start,
            work_end: item.work_end || item.aps_end,
          }
        });
        this.file = file;
        this.threed_file = threed_file;
      })
      this.setActiveIndex(0);
    })
  }

  @action.bound
  submit() {
    const { id, capacity, batch_order_num, work_device_id, work_user_id, work_station_id, work_line_id, work_start, work_end } = this.activeBatchOrder;
    this.loading = true;
    this.service.assignmentTask({
      id,
      capacity,
      batch_order_num,
      work_device_id,
      work_user_id,
      work_station_id,
      work_line_id,
      work_start: getDateTime(work_start),
      work_end: getDateTime(work_end)
    }).then(() => {
      message.success('提交成功');
    }).finally(() => {
      this.loading = false;
    });
  }

  @action.bound
  dispatch(payload: any) {
    this.dialogLoading = true;
    const { id, capacity, batch_order_num } = this.activeBatchOrder;
    this.service.assignmentTask({
      id,
      capacity,
      batch_order_num,
      ...payload
    }).then(() => {
      message.success('提交成功');
      this.visible = false;
      this.getTaskResourceOccupyInfo(id);
    }).finally(() => {
      this.dialogLoading = false;
    })
  }
}
